package org.mtmi.ui.controls;

import org.mtmi.ui.IAdaptable;
import org.mtmi.ui.controls.listeners.ControlDisposedListener;
import org.mtmi.ui.controls.listeners.DisposeEvent;
import org.mtmi.ui.controls.listeners.ValueChangedListener;
import org.mtmi.ui.controls.listeners.ValueEvent;
import org.mtmi.ui.scenes.Scene;


public abstract class AbstractValueControlledControl extends Control 
 implements ValueChangedListener, ControlDisposedListener
{
	private int valCurrent;
	private IValueGenerator ctr_value;
	private String ctr_value_connection_id;
	
	
	public AbstractValueControlledControl( Scene scene, int _flags ) {
		super( scene, _flags );
	}

	/** @return current value */
	public int getValue() { return valCurrent; }
	
	/** Change value, redraw control */
	public void setValue( int val ) {
		if( val!=valCurrent ) {
			valCurrent = val;
			redraw();
		}
	}
	
//TODO: this might be shared with AbstractRangeValueControl ... but LEDBG is not ValueGenerator	
	public IValueGenerator getValueController() { return ctr_value; }
	public String getValueControllerConnectionId() { return ctr_value_connection_id; }
	
	public void setValueController( IValueGenerator ctr, String cid ) { 
		if( ctr_value!=null ) {
			if( ctr_value instanceof IAdaptable ) {
				Control c = (Control) ((IAdaptable)ctr_value).getAdapter( Control.class, null );
				if( c!=null ) {
					c.removeControlDisposedListener( this );
				}
			}
			ctr_value.removeValueChangedListener( this );
		}
		ctr_value = ctr;
		ctr_value_connection_id = cid;
		if( ctr_value != null ) {
			if( ctr_value instanceof IAdaptable ) {
				Control c = (Control) ((IAdaptable)ctr_value).getAdapter( Control.class, null );
				if( c!=null ) {
					c.addControlDisposedListener( this );
				}
			}
			ctr_value.addValueChangedListener( this );
			valueControllerValueChanged(); //assign current value
		}
	}
	
	@Override
	public void controlDisposed(DisposeEvent event) {
		if( event.control == ctr_value ) {
			ctr_value.removeValueChangedListener( this );
			ctr_value = null;
		}
	}
	
	@Override
	public void valueChanged(ValueEvent event) {
		if( event.value_generator == ctr_value ) {
			valueControllerValueChanged();
		}
	}
	
	/** by default scale controller value to range 0..100, bounded subclasses must override */
	protected void valueControllerValueChanged() {
		float k = ctr_value.getValueF();
		//the default range is [0..100]
		int value = Math.round( 100*k );
		setValue( value );
	}

	
	
}
